package com.jse.web;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collection;
import java.util.Map;

import com.jse.Fs;
import com.jse.Js;
import com.jse.Jse;
import com.jse.Lang;
import com.jse.Log;
import com.jse.jdbc.Pager;
import com.jse.json.JsonObject;

public class Action {
	
	private final static Log log=Log.get("web");

	public static void service(Ctx ex) throws IOException {
		if(!Web.ipCheck(ex))return;//IP功能
		Web.cors(ex);//设置跨域
		String path=ex.getPath();
		String suffix=ex.getSuffix();
		if(Web.isStatic(path,suffix)) {//静态
			View.staticforward.render(ex,path);
			return;
		}
		long starttime=System.currentTimeMillis();
		try {
			if(path.equals("/jse")) {
				Js.execute(Fs.read(Jse.jspath()+"/jse.js"));
				View.json.render(ex,"{\"code\":0,\"msg\":\"jse.js init\"}");return;
			}else if(path.equals("/jse/up")) {
				View.json.render(ex,new JsonObject().add("code",0).add("data",ex));return;
			}
//			else if(path.equals("/jse/code")) {//code环境
//				View.html.render(ex);
//			}else if(path.equals("/jse/log")) {//日志
//				View.html.render(ex);
//			}
			else if(path.equals("/jse/gitee")) {//gitee
				View.json.render(ex,Js.fun("gitee",ex));
				return;
			}
			else if(path.startsWith("/jse/captcha")) {//暂时简单实现
				var code=path.substring(12);
				if(code.length()>1){code=code.substring(1);}
				else {
					var c=ex.get("code");
					if(c==null) {code=Lang.randomString(4);}
					else code=c.toString();
				}
				View.captcha.render(ex,code);
				return;
			}
			ScopedValue.where(Web.RQS,ex).call(()->{
			if(!Web.filter(ex,true)) {
				return null;
			}
			if("vue".equals(suffix)){
				vue(ex);
			}else if(suffix.length()==0||"html".equals(suffix)){//后缀空
				try {
					empty(ex);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}else if("json".equals(suffix)){
				var json=Jse.webapp(ex.getServerName())+path;
				var json1=Jse.jspath(ex.getServerName())+path;
				var json2=json1.substring(0,json1.length()-2);
				if(Fs.exists(json)) {
					View.json.render(ex,Fs.read(json));
				}else if(Fs.exists(json1)) {
					View.json.render(ex,Fs.read(json1));
				}else if(Fs.exists(json2)) {
					try {
						empty(ex);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}else {
					View.json.render(ex,"{\"code\":404}");
				}
			}else {
				var webapp=Jse.webapp(ex.getServerName());
				var p=Path.of(webapp,path);
				if(Files.exists(p)) {
					View.staticforward.render(ex,path);
					return null;
				}
				var jspath=Jse.jspath(ex.getServerName());
				var js=Path.of(jspath,ex.getMapping()+".js");
				if(Files.exists(js)){
					View.ret.render(ex,Js.cFun(js,suffix,ex));
				}
			}
			return Web.filter(ex,false);
			});
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			log.debug("%s:%s %dms",ex.getMethod(),path,(System.currentTimeMillis()-starttime));
		}
	}
	
	private static void vue(Ctx tbl) throws IOException {//处理vue
		String mapping=tbl.getMapping();
		var jspath=Jse.jspath(tbl.getServerName());
		var webapp=Jse.webapp(tbl.getServerName());
		var vue=Path.of(jspath,mapping.concat(".vue"));
		if(Files.exists(vue)) {
			var s=Fs.readString(jspath,mapping.concat(".vue"),Map.of("tpl","js","p",tbl));
			View.text.render(tbl,s);
		}
		vue=Path.of(webapp,mapping+".vue");
		if(Files.exists(vue)){
			var s=Fs.readString(webapp,mapping.concat(".vue"),Map.of("tpl","js","p",tbl));
			View.text.render(tbl,s);
		}
	}
	
	private static void empty(Ctx tbl) throws Exception {//默认空后缀
		try {
			var jspath=Jse.jspath(tbl.getServerName());
				String mapping=tbl.getMapping();
				tbl.setAttribute("p",tbl);
				var webapp=Jse.webapp(tbl.getServerName());
				var js=Path.of(jspath+mapping+".js");
				Object obj=null;
				if(Files.exists(js)) {
					try {
						obj=Js.cFun(js,"main",new Object[]{tbl});
					} catch (Exception e) {
						e.printStackTrace();
						throw new RuntimeException(e);}
				}
				var ht=Lang.def(tbl.getAttribute("@page"),mapping+".html");
				var htm=webapp+ht;
				var htmm=webapp+"/"+Web.mobile_dir+ht;//手机端页面
				if(obj instanceof View v)v.render(tbl,null);
				else if("json".equals(tbl.getSuffix())) {
					View.json.render(tbl,obj);
				}
				else if(obj instanceof String s) {
					View.str.render(tbl,s);
				}
				else if(Web.has_mobile&&tbl.isMobile()&&Files.exists(Path.of(htmm))) {
					tbl.setAttribute("obj",obj);View.tpl.render(tbl,htmm);
				}else if(Files.exists(Path.of(htm))) {
					try {
						tbl.setAttribute("obj",obj);
						View.tpl.render(tbl,htm);
					} catch (Throwable e) {
						e.printStackTrace();
					}
				}else if(Files.exists(Path.of(jspath,mapping+".vue"))) {
					if(Files.exists(Path.of(jspath,"vue.html"))) {
						View.tpl.render(tbl,Jse.jspath+"/vue.html");
					}else {
						var s=Fs.readString(jspath,mapping+".vue",Map.of("tpl","js","p",tbl));
						View.text.render(tbl,s);
					}
				}else if(Files.exists(Path.of(webapp,mapping+".vue"))) {
					var s=Fs.readString(webapp,mapping+".vue",Map.of("tpl","js","p",tbl));
					View.text.render(tbl,s);
				}else if(Files.exists(Path.of(jspath+mapping+".html"))) {
					View.tpl.render(tbl,jspath+mapping+".html");
				}
				else if(obj instanceof Map||obj instanceof Collection||obj instanceof Pager) {
					View.json.render(tbl, obj);
				}
				else {
					View.not.render(tbl,null);
				}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
